var Util = require('../../utils/util.js');
import {
	add,
	accMul,
	accSubtr 
} from "../../utils/customUtil.js"
const app = getApp()
Page({
	data: {
		focus:false,
		values: '', // 留言输入框绑定值
		iosdata: '', // iso不显示购买按钮
		iosX:'',
		lens: null, // 选集长度
		playimg: '', // 视频链接
		autoplay: false, // 是否播放
		writingLen: 0,
		isTabFaxed:false,
		defaultHeading: "../../public/img/favicon.ico", // 留言默认头像
		liuyanShow: false, // 留言弹框
		liuyanData: '', // 留言内容
		tabshow: 0,
		tabshow1:1,
		token: '',
		page: 1, //评论页码
		last_page: "",
		aid: '', // 视频介绍id
		discount: 0, //优惠多少钱
		videoIndex: "", //当前播发的序号
		list: [], // 组合列表数组数据
		listdata: {}, // 存储组合列表返回所有数据
		videoshow: 0, // 显示视频播放
		playvideo: '', // 视频播放链接
		detailObj: {}, // 存储详情返回数据
		navBarHeight: app.globalData.navBarHeight,
		ids: '', //  详情对应id
		videoContent: [], // 解密后的详情数据
		videohtml: '', // 收费视频转换富文本
		handleintro: '', // 免费视频介绍
		messageList: {}, // 留言列表数据
		messageKey: [], // 解密后的留言列表数据
		isShow: true, // 组合购买弹窗

		scene: '../../public/img/UIimg/picture_erweima_kechengjieshao.png',
		show_web: true,
		QRshow: false, // 咨询弹框
	},

	goDetail(e){
		let ids = e.target.dataset.key
		 console.log(ids)
		 wx.navigateTo({
			url: `/pages/listdetail/listdetail?ids=${ids}`
		});
	 },
	// 详情接口函数
	listDetail(e) {
		let token = wx.getStorageSync("token") ? JSON.parse(wx.getStorageSync("token")) : ''
		let that = this;
		wx.request({
			url: 'https://api.jiudaifu.com/v2/acupoint/subject/info2',
			data: {
				id: that.data.ids,
				planteform: 'android',
				username: token.uid
			},
			header: {
				'content-type': 'application/json', // 默认值
				'Authorization': 'Bearer ' + token.token
			},
			success: function (res) {
				console.log("详情返回数据", res.data.data);
				let restr = res.data.data.subject.intro
				let str = restr.replace(/【/g, "<br>【");

				let arr = res.data.data.contents

				const maparr = arr.map(item => ({
					...item,
					isActive: false,
					video: Util.decodeParam(item.video)
				}))
				let lens = maparr.length
				let playimg = maparr[0].cover
				console.log(playimg)


				that.setData({
					detailObj: res.data.data,
					videoContent: maparr,
					handleintro: str,
					aid: res.data.data.subject.introduce_id,
					lens,
					playimg
				})
				var This = this;
				wx.createSelectorQuery().select('#headerTop').boundingClientRect(function (rect) {
					that.setData({
						tabH: rect.height
					})
				}).exec()

				that.getList()
			//	console.log('收费视频介绍id传参', that.data.aid)

				// 收费视频介绍接口
				wx.request({
					url: 'https://mall.jiudafu.com/admin/article.php?is_ajax=1&act=get_document_article_content',
					data: {
						aid: that.data.aid
					},
					method: 'GET',
					header: {
						'content-type': 'application/json', // 默认值
					},
					success: function (res) {
					//	 console.log("收费视频介绍返回数据", res.data.content);
					
						that.setData({
							videohtml: res.data.content
						})
					},
					fail: function (res) {
						console.log(res)
					}
				});
			},
			fail: function (res) {
				console.log(res)
			}
		});
	},
	aa1(){
		wx.switchTab({
			url: '/pages/index/index',
			success: function(e) {
				var page = getCurrentPages().pop();
				if (page == undefined || page == null) return;
				page.onLoad();
			}
		})
	},
	//  咨询弹框
	zixun() {
	
		let token = wx.getStorageSync("token") ? JSON.parse(wx.getStorageSync("token")) : '';
		if (!token) {
			app.goLogin()
		} else {
			this.setData({
				QRshow: true
			})
		}
	},
	// 跳转订单详情   组合弹窗的下一步
	gobuy() {
		//		console.log(this.data.list.length)
    
		var arr1 = [];
		this.data.list.forEach(v => {
			if (v.checked) {
				arr1.push(v.id)
			}
		})
		let arr2 = arr1.join(",");
		//	console.log(arr2)
		if (arr1.length == 0) {
			let sumPrice = Number(this.data.detailObj.subject.price);
			wx.setStorageSync('sumPrice', sumPrice);
			wx.setStorageSync('discountPrice', sumPrice);
			wx.setStorageSync('discount', 0);
		}
		this.setData({
			isShow: false,
			discount: 0
		})
		wx.navigateTo({
			url: '/pages/order/order?ids=' + arr2 + "&id=" + this.data.ids
		});
	},
	// 手动播放按钮
	fixclick(){
		this.setData({
			playvideo: this.data.videoContent[0].video,
			videoshow: 1,
			autoplay: true
		})
	},
	// tab栏切换
	cutTab(e) {
		var that = this;
		if (e.currentTarget.dataset.key == 1 && this.data.videoIndex == '') {
			// 选集播放第一个
			this.setData({
				playvideo: this.data.videoContent[0].video,
				videoshow: 1,
				videoIndex: 0,
				autoplay: true
			})
		}
		this.setData({
			tabshow: e.currentTarget.dataset.key
		})
    if(e.currentTarget.dataset.key == 2){
			that.setData({
				tabshow1: 2
			})
		}
		wx.createSelectorQuery().select('#headerTop').boundingClientRect(function (rect) {
			that.setData({
				tabH: rect.height
			})
		}).exec()
	},
	// 视频播放按钮
	play(e) {
		let showkey = e.currentTarget.dataset.key;
		let index = e.currentTarget.dataset.index;
		this.setData({
			playvideo: showkey,
			videoshow: 1,
			videoIndex: index,
			autoplay: true
		})
	},

	// 视频播放完播放下一个
	endVideo() {
		let index = this.data.videoIndex + 1;
		if (this.data.videoContent.length == index) {
			console.log('已经是最后一个了')
			return;
		}

		if (this.data.detailObj.subject.free == 1 && this.data.detailObj.subject.hasBuy == 0) {
			console.log('要付费才能观看');
			this.setData({
				playvideo: this.data.videoContent[index].video,
				videoshow: 1,
				videoIndex: index,
				autoplay: false
			})
		} else {
			this.setData({
				playvideo: this.data.videoContent[index].video,
				videoshow: 1,
				videoIndex: index,
				autoplay: true
			})
		}

	},

	//  遮罩层关闭咨询弹框
	closeQR() {
		this.setData({
			QRshow: false
		})
	},
	// 组合购买列表接口
	getList() {
		let token = wx.getStorageSync("token") ? JSON.parse(wx.getStorageSync("token")) : ''
		let that = this;
		wx.request({
			url: 'https://api.jiudaifu.com/v2/acupoint/subject/activitylist',
			data: {
				planteform: 'android',
				username: token.uid
				// username: '20140010',
			},
			method: 'GET',
			header: {
				'content-type': 'application/json', // 默认值
			},
			success: function (res) {
				console.log("组合推荐列表返回数据", res.data.data);
				let list = res.data.data.list;
				list.map(item => {
					item['checked'] = false
				})
				var listA = []
				list.forEach(item => {
					if (item.id != that.data.detailObj.subject.id) {
						listA.push(item)
					}
				})
				that.setData({
					list: listA,
					listdata: res.data.data
				})

			},
			fail: function (res) {
				console.log(res)
			}
		});
	},
	//监听评论输入
	watchPl(e) {
		var value = e.detail.value;
		this.setData({
			writingLen: value.length
		})
	},

	// 复选框事件
	listenCheckboxChange(e) {
		let index = e.currentTarget.dataset.index;
		let list = this.data.list
		//	console.log(e.detail.value)
		if (e.detail.value.length == 0) {
			list[index].checked = false;
			this.setData({
				discount: 0
			})
		}
		if (e.detail.value[0] == 'false') {
			list[index].checked = true;
			console.log('-------------')
		}
		this.setData({
			list
		})
		this.getPrice()
	},

	// 计算价格
	getPrice() {
		let len = 0;
		let sumPrice = Number(this.data.detailObj.subject.price);
		let discountPrice = 0;
		this.data.list.forEach(v => {
			if (v.checked) {
				len++;
				sumPrice = add(sumPrice, Number(v.price))
			}
		})
		if (len >= 2) {
			discountPrice = accMul(sumPrice, this.data.listdata.activity_3)
		} else if (len == 1) {
			discountPrice = accMul(sumPrice, this.data.listdata.activity_2)
		}
		// 优惠价 =  总价  -  折扣价
		console.log(sumPrice, discountPrice)
		wx.setStorageSync('sumPrice', sumPrice);
		wx.setStorageSync('discountPrice', discountPrice)
		wx.setStorageSync('discount', discountPrice ? accSubtr(sumPrice, discountPrice) : 0)
		this.setData({
			discount: discountPrice ? accSubtr(sumPrice, discountPrice) : 0
		})
	},
	// 遮罩层关闭组合弹窗
	go_pay1() {
		this.setData({
			isShow: false
		})
	},
	// 弹出支付接口
	go_pay() {
		let discount = wx.getStorageSync("discount") ? wx.getStorageSync("discount") : '';
		let token = wx.getStorageSync("token") ? JSON.parse(wx.getStorageSync("token")) : '';
		let list = this.data.list;
		let len = this.data.list.length;
		if (!token) {
			app.goLogin()
		} else {
			list.map(item => {
				 item['checked'] = false
				// if(item['checked']){
				// 	return
				// }else{
				// 	item['checked'] = false
				// 	this.setData({ 
				// 		list,
				// 		discount: 0
				// 	})
				// }
			})
			if (len == 0) {
				// this.setData({ 
				// 	list,
				// 	discount: 0
				// })
				// wx.navigateTo({
				// 	url: '/pages/order/order',
				// })







				var arr1 = [];
				this.data.list.forEach(v => {
					if (v.checked) {
						arr1.push(v.id)
					}
				})
				let arr2 = arr1.join(",");
				//	console.log(arr2)
				if (arr1.length == 0) {
					let sumPrice = Number(this.data.detailObj.subject.price);
					wx.setStorageSync('sumPrice', sumPrice);
					wx.setStorageSync('discountPrice', sumPrice);
					wx.setStorageSync('discount', 0);
				}
				this.setData({
					// isShow: false,
					discount: 0
				})
				wx.navigateTo({
					url: '/pages/order/order?ids=' + arr2 + "&id=" + this.data.ids
				});












			} else {
				this.setData({
					isShow: true,
					list,
					discount: 0
				})
			}
		}
	},
	// 付费视频接口函数
	// getVIPvideo() {
	// 	//  console.log(this.data.aid,'*********')
	// 	let that = this;
	// 	wx.request({
	// 		url: 'https://mall.jiudafu.com/admin/article.php?is_ajax=1&act=get_document_article_content',
	// 		data: {
	// 			aid: this.data.detailObj.subject.introduce_id
	// 		},
	// 		method: 'GET',
	// 		header: {
	// 			'content-type': 'application/json', // 默认值
	// 		},
	// 		success: function (res) {
	// 			console.log("收费视频介绍返回数据", res.data.content);
	// 			//  that.videohtml = res.data.content;
	// 			that.setData({
	// 				videohtml: res.data.content
	// 			})
	// 		},
	// 		fail: function (res) {
	// 			console.log(res)
	// 		}
	// 	});
	// },

	// 弹出写评论窗口
	bindKeyInput() {
		 let that = this;
		this.setData({
			liuyanShow: !that.data.liuyanShow,
			values: '',
			focus:true
		})
		// let token = wx.getStorageSync("token") ? JSON.parse(wx.getStorageSync("token")) : '';
		// if (!token) {
		// 	app.goLogin()
		// } else {
		// 	this.setData({
		// 		liuyanShow: !that.data.liuyanShow,
		// 		values: ''
		// 	})
		// }
	},
	// 提交评论
	submitMessage(e) {
		let that = this;
		if (!e.detail.value.textarea) {
			wx.showToast({
				title: '您暂未留言',
				icon: 'errpr',
				duration: 500
			})
			return
		}
		let token = wx.getStorageSync("token") ? JSON.parse(wx.getStorageSync("token")) : ''
		console.log(e.detail.value.textarea)

		wx.request({
			url: 'https://api.jiudaifu.com/v2/acupoint/subject/comment',
			data: {
				id: that.data.ids,
				comment: e.detail.value.textarea
			},
			method: 'post',
			header: {
				'content-type': 'application/json', // 默认值
				'Authorization': 'Bearer ' + token.token
			},
			success: function (res) {
				console.log("提交留言返回数据", res);
				that.setData({
					liuyanShow: false
				})
				that.getMessageList()
			},
			fail: function (res) {
				console.log(res)
			}
		});
	},
	// 图片加载异常的事件
	errorFunction: function (e) {
		const that = this;
		if (e.type == "error") {
			//获取错误图片循环的下标
			const errorImgIndex = e.target.dataset.errorimg;
			const messageKey = that.data.messageKey;
			//错误图片替换为默认图片
			messageKey[errorImgIndex][`headimg`] = that.data.defaultHeading;
			that.setData({
				messageKey: messageKey
			})
		}
	},
	// 留言列表接口
	getMessageList() {
		let token = wx.getStorageSync("token") ? JSON.parse(wx.getStorageSync("token")) : ''
		let that = this;
		wx.request({
			url: 'https://api.jiudaifu.com/v2/acupoint/subject/comment',
			data: {
				id: this.data.ids,
				page: this.data.page
			},
			method: 'GET', 
			header: {
				'content-type': 'application/json', // 默认值
				'Authorization': 'Bearer ' + token.token
			},
			success: function (res) {
			//	console.log("留言列表返回数据", res.data.data);

				let arr = res.data.data.data
				const maparr = arr.map(item => ({
					...item,
					content: decodeURIComponent(item.content),
					time: Util.getTimeData(item.time),
				}))
				let lens1 = maparr.length;
				console.log(that.data.page)
				let page = that.data.page+1;
				that.setData({
					messageList: res.data.data,
					messageKey: [...that.data.messageKey, ...maparr],
					lens1,
					last_page: res.data.data.last_page,
					page
				})
				console.log('解密后的留言列表数据',that.data.messageKey)
			},
			fail: function (res) {
				console.log(res)
			}
		});
	},

	// 视频点赞
	getlike1(e) {
		let that = this;
		let {
			id,
			like
		} = e.target.dataset.obj.subject;
		console.log('id and like', id, like)
		// like  0 表示没点  1表示已点

		let token = wx.getStorageSync("token") ? JSON.parse(wx.getStorageSync("token")) : ''
		//	console.log(token)
		if (!token) {
			app.goLogin()
		} else {
			wx.request({
				url: 'https://api.jiudaifu.com/v2/acupoint/subject/like',
				data: {
					id:id,
					type: like == 1 ? 2 : 1				
				},
				method: 'get',
				header: {
					'content-type': 'application/json', // 默认值
					'Authorization': 'Bearer ' + token.token
				},
				success: function (res) {
					console.log("视频点赞或取消成功", res);
					that.listDetail();
				},
				fail: function (res) {
					console.log(res)
				}
			});
		}
	},

	// 评论点赞
	getlike2(e) {
		let that = this;
		let {
			id,
			like
		} = e.target.dataset.keys;
		console.log('id and like', id, like)
		// like  0 表示没点  1表示已点

		let token = wx.getStorageSync("token") ? JSON.parse(wx.getStorageSync("token")) : ''
		//	console.log(token)
		if (!token) {
			app.goLogin()
		} else {
			wx.request({
				url: 'https://api.jiudaifu.com/v2/acupoint/subject/comment/like',
				data: {
					cid: id,
					type: like == 1 ? 2 : 1
				},
				method: 'get',
				header: {
					'content-type': 'application/json', // 默认值
					'Authorization': 'Bearer ' + token.token
				},
				success: function (res) {
					console.log("评论点赞或者取消点赞成功", res);
          for (var i = 0; i < that.data.messageKey.length; i++) {  
            if (that.data.messageKey[i].id == id) {
              console.log(like,'like---')
              if (like == "0") {
                that.data.messageKey[i].likes += 1;
                that.data.messageKey[i].like = 1;
              } else {
                that.data.messageKey[i].likes -= 1;
                that.data.messageKey[i].like = 0;
              }
            }
          }
          that.setData({
            messageKey: that.data.messageKey,
          })
				},
				fail: function (res) {
					console.log(res)
				}
			});
		}
	},
	/**
	 * 
	 */
  
	//取消事件
	_cancelEvent() {
		this.dialog.hideDialog();
	},

	onLoad: function (options) {
		let that = this
		// 记录用户手机型号
		wx.getSystemInfo({
			success: function (res) {
				console.log('匹配机型数据',res)
				that.setData({
					iosdata: res.platform,
					iosX:res.model
				})
			}
		});
		// console.log(options)
		this.setData({
			ids: options.ids || 1
		})
	// 分享事件配置
			wx.showShareMenu({
				withShareTicket: true
			})
	},
 
			
	
	xf(){
			console.log(111)
			return
	},
	  //	用户点击分享按钮分享
	onShareAppMessage: function () {
		return {
			title: '分享标题',
			path: 'pages/home/index',
			imageUrl: '../../public/img/zx_bg.png',
			success: (res) => {
				// 分享成功
			},
			fail: (res) => {
				// 分享失败
			}
		}
	},
		// 图片识别
	click2() {
		this.setData({
			show_web: true
		})

	},
		// 图片识别
		previewImage: function (e) {
			wx.previewImage({
				urls: this.data.scene.split(',')
				// 需要预览的图片http链接  使用split把字符串转数组。不然会报错
			})
		},
	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {
		console.log(this.data.page,this.data.last_page)
		if (this.data.tabshow == 2) {
			if (this.data.page - 1 != this.data.last_page) {
				this.getMessageList()
			}else {
				console.log('没有更多数据了')
			}
		} 

	},
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {
		//获得dialog组件
		this.dialog = this.selectComponent("#dialog");
	},
	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {
		this.listDetail();
		this.getMessageList();
		// this.getVIPvideo();
	},
	
	onPageScroll(e){
		var This = this;
		wx.createSelectorQuery().select('.videoPlaydesc').boundingClientRect(function (rect) {
			if(e.scrollTop>=rect.height){
				This.setData({
					isTabFaxed:true
				})
			}else{
				This.setData({
					isTabFaxed:false
				})
			}
		}).exec()
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {

	},

})